package org.example.traffic.questions;

import org.example.traffic.organizationadmin.OrganizationAdmin;
import org.example.traffic.questions.Questions;
import org.example.traffic.questions.QuestionsRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class QuestionsService {

    private final QuestionsRepository questionsRepository;

    public QuestionsService(QuestionsRepository questionsRepository) {
        this.questionsRepository = questionsRepository;
    }

    // 获取所有问题
    public List<Questions> getAllQuestions() {
        return questionsRepository.findAll();
    }

    // 根据ID获取问题
    public Optional<Questions> getQuestionById(Integer id) {
        return questionsRepository.findById(id);
    }

    // 创建新的问题
    public Questions createQuestion(Questions question) {
        return questionsRepository.save(question);
    }


    // 删除问题
    public boolean deleteQuestion(Integer id) {
        if (questionsRepository.existsById(id)) {
            questionsRepository.deleteById(id);
            return true;
        } else {
            return false;
        }
    }
    /**
     * 根据题目名称进行模糊查询
     * @param questionText 题目名称（模糊匹配）
     * @return 符合条件的题目列表
     */
    public List<Questions> findQuestionsByText(String questionText) {
        return questionsRepository.findByQuestionTextContaining(questionText);
    }
    /**
     * 验证答案是否正确
     * @param questionId 题目ID
     * @param userAnswer 用户提交的答案
     * @return 如果答案正确返回true，否则返回false
     */
    public boolean validateAnswer(Integer questionId, String userAnswer) {
        Optional<Questions> questionOptional = questionsRepository.findById(questionId);
        if (questionOptional.isPresent()) {
            Questions question = questionOptional.get();
            return question.getCorrectAnswer().equalsIgnoreCase(userAnswer); // 忽略大小写比较
        }
        return false; // 如果题目不存在，返回false
    }

    public Questions updateQuestion(Integer id, Questions updatedQuestion) {
        Optional<Questions> questionOptional = questionsRepository.findById(id);
        if (questionOptional.isPresent()) {
            Questions question = questionOptional.get();
            // 更新除 id 外的所有字段
            question.setQuestionText(updatedQuestion.getQuestionText());
            question.setOptionA(updatedQuestion.getOptionA());
            question.setOptionB(updatedQuestion.getOptionB());
            question.setOptionC(updatedQuestion.getOptionC());
            question.setOptionD(updatedQuestion.getOptionD());
            question.setCorrectAnswer(updatedQuestion.getCorrectAnswer());
            question.setPoints(updatedQuestion.getPoints());
            question.setOrganization(updatedQuestion.getOrganization());
            question.setContent(updatedQuestion.getContent());
            return questionsRepository.save(question);
        }
        return null; // 如果题目不存在，返回 null
    }
    /**
     * 计算用户提交答案的总分
     * @param answers 用户提交的答案列表
     * @return 返回用户总分
     */
    public int calculateTotalScore(List<Map<String, Object>> answers) {
        int totalScore = 0;
        for (Map<String, Object> answer : answers) {
            Integer questionId = (Integer) answer.get("questionId");
            String userAnswer = (String) answer.get("userAnswer");
            Optional<Questions> questionOptional = questionsRepository.findById(questionId);
            if (questionOptional.isPresent()) {
                Questions question = questionOptional.get();
                if (question.getCorrectAnswer().equalsIgnoreCase(userAnswer)) {
                    totalScore += question.getPoints(); // 答案正确，累加分值
                }
            }
        }
        return totalScore;
    }
    // 分页查询视频
    public Page<Questions> getQuestions(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return questionsRepository.findAll(pageable);
    }
}

